﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using DAL;
using MS_Entity;

namespace MS_UI
{
    public static class CommonMethod
    {
        // 登录用户对象
        public static SysAdmins objAdmins;
        // 从站地址
        public static int Address = 0;
        // 创建ModbusEntity对象
        public static ModbusEntity objModbusEntity = new ModbusEntity();
        // 变量信息集合
        public static List<Variable_Modbus> VarModbusList = new List<Variable_Modbus>();
        // 报警变量集合
        public static List<VarAlarm_Modbus> VarAlarmModbusList = new List<VarAlarm_Modbus>();
        // 存储区域集合
        public static List<StoreArea> StoreAreaList = new List<StoreArea>();
        // 变量名和数值的字典集合
        public static Dictionary<string, string> CurrentValue = new Dictionary<string, string>();
        // 变量名和地址的字典集合
        public static Dictionary<string, string> CurrentVarAddress = new Dictionary<string, string>();
        // 归档变量集合
        public static List<Variable_Modbus> FileVarModbusList = new List<Variable_Modbus>();
        // 数据报表变量集合
        public static List<Variable_Modbus> ReportVarModbusList = new List<Variable_Modbus>();
        // 创建Modbus实列
        public static Modbus objMod = new Modbus();
        // 创建通讯状态标志位
        public static bool CommOK = false;
        // 创建数据写入的标志位
        public static bool IsWriting = false;
        // 趋势缓冲区
        public static List<List<Cache>> CacheList = new List<List<Cache>>();
        // 定义缓冲区大小（每秒一条）
        public static int CacheCount = 600;
        // 定义变量名称和注释的键值对
        public static Dictionary<string, string> CurrentVarNote = new Dictionary<string, string>();
        // 定义所有变量名称的集合
        public static List<string> FileVarNameList = new List<string>();

        #region 获取通讯信息
        /// <summary>
        /// 获取通讯信息
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static ModbusEntity GetConfigInfo(string filename)
        {
            FileStream fs = new FileStream(filename,FileMode.Open);
            StreamReader sr = new StreamReader(fs,Encoding.Default);
            List<string> list = new List<string>();
            while (true)
            {
                string str = sr.ReadLine();
                if (str == null)
                {
                    break;
                }
                else
                {
                    list.Add(str);
                }
            }
            ModbusEntity objModbus = new ModbusEntity();
            if (list.Count == 6)
            {
                objModbus.Port = list[0];
                Address = Convert.ToInt32(list[1]);
                objModbus.Paud = Convert.ToInt32(list[2]);
                objModbus.DataBit = Convert.ToInt32(list[4]);
                switch (list[3])
                {
                    case "None":
                        objModbus.IParity = Parity.None;
                        break;
                    case "Even":
                        objModbus.IParity = Parity.Even;
                        break;
                    case "Odd":
                        objModbus.IParity = Parity.Odd;
                        break;
                    default:
                        objModbus.IParity = Parity.None;
                        break;
                }
                switch (list[5])
                {
                    case "1":
                        objModbus.IStopbit = StopBits.One;
                        break;
                    case "2":
                        objModbus.IStopbit = StopBits.Two;
                        break;
                    default:
                        objModbus.IStopbit = StopBits.One;
                        break;
                }
            }
            return objModbus;
        }
        #endregion

        #region 向XML文件中添加节点属性信息
        public static void XMLAttibuteAppend(XmlDocument rootxml, string name, string value, XmlElement head)
        {
            XmlAttribute att = rootxml.CreateAttribute(name);
            att.Value = value;
            head.Attributes.Append(att);
        }
        #endregion

        #region 根据节点及节点名称获取相应的值
        /// <summary>
        /// 根据节点及节点名称获取相应的值
        /// </summary>
        /// <param name="rootxml"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string XMLAttributeGetValue(XmlNode rootxml, string name)
        {
            string resvalue = string.Empty;
            if (rootxml != null && rootxml.Attributes != null && rootxml.Attributes[name] != null)
            {
                resvalue = rootxml.Attributes[name].Value;
            }
            return resvalue;
        }
        #endregion

        #region 根据Modbus变量路径返回变量集合
        public static List<Variable_Modbus> LoadXML(string xmlpath)
        {
            List<Variable_Modbus> VarModbusList = null;
            if (!File.Exists(xmlpath))
            {
                MessageBox.Show("IO配置变量的XML文件不存在");
            }
            else
            {
                VarModbusList = new List<Variable_Modbus>();
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlpath);
                foreach (XmlNode nodeRoot in xdoc.ChildNodes)
                {
                    if (nodeRoot.Name == "Root")
                    {
                        foreach (XmlNode noodchild in nodeRoot.ChildNodes)
                        {
                            if (noodchild.Name == "Variable")
                            {
                                Variable_Modbus objVar = new Variable_Modbus();
                                objVar.VarName = XMLAttributeGetValue(noodchild, "VarName");
                                objVar.Address = XMLAttributeGetValue(noodchild, "Address");
                                objVar.DataType = XMLAttributeGetValue(noodchild, "DataType");
                                objVar.StoreArea = XMLAttributeGetValue(noodchild, "StoreArea");
                                objVar.IsFilling = XMLAttributeGetValue(noodchild, "IsFilling");
                                objVar.IsAlarm = XMLAttributeGetValue(noodchild, "IsAlarm");
                                objVar.IsReport = XMLAttributeGetValue(noodchild, "IsReport");
                                objVar.Note = XMLAttributeGetValue(noodchild, "Note");
                                objVar.AbsoluteAddress = XMLAttributeGetValue(noodchild, "AbsoluteAddress");
                                VarModbusList.Add(objVar);
                            }
                        }
                    }
                }
            }
            return VarModbusList;
        }
        #endregion

        #region 根据XMLAlarm文件路径返回报警变量
        public static List<VarAlarm_Modbus> LoadAlarmXml(string xmlpath)
        {
            List<VarAlarm_Modbus> VarAlarmList = null;
            if (!File.Exists(xmlpath))
            {
                MessageBox.Show("IO配置报警变量的XML文件不存在");
            }
            else
            {
                VarAlarmList = new List<VarAlarm_Modbus>();
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlpath);
                foreach (XmlNode nodeRoot in xdoc.ChildNodes)
                {
                    if (nodeRoot.Name == "Root")
                    {
                        foreach (XmlNode noodchild in nodeRoot.ChildNodes)
                        {
                            if (noodchild.Name == "VarAlarm")
                            {
                                VarAlarm_Modbus objVar = new VarAlarm_Modbus();
                                objVar.VarName = XMLAttributeGetValue(noodchild, "VarName");
                                objVar.VarAlarm = GetAlarm(XMLAttributeGetValue(noodchild, "Alarm"));
                                VarAlarmList.Add(objVar);
                            }
                        }
                    }
                }
            }
            return VarAlarmList;
        }
        #endregion

        #region 根据存储区路径路径返回存储区集合
        public static List<StoreArea> LoadStoreAreaXML(string xmlpath)
        {
            List<StoreArea> StoreAreaList = null;
            if (!File.Exists(xmlpath))
            {
                MessageBox.Show("存储区的XML文件不存在");
            }
            else
            {
                StoreAreaList = new List<StoreArea>();
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlpath);
                foreach (XmlNode nodeRoot in xdoc.ChildNodes)
                {
                    if (nodeRoot.Name == "Root")
                    {
                        foreach (XmlNode noodchild in nodeRoot.ChildNodes)
                        {
                            if (noodchild.Name == "StoreArea")
                            {
                                StoreArea objVar = new StoreArea();
                                objVar.StoreType = XMLAttributeGetValue(noodchild, "StoreType");
                                objVar.StartReg = int.Parse(XMLAttributeGetValue(noodchild, "StartReg"));
                                objVar.Length = int.Parse(XMLAttributeGetValue(noodchild, "Length"));
                                StoreAreaList.Add(objVar);
                            }
                        }
                    }
                }
            }
            return StoreAreaList;
        }
        #endregion

        #region 根据字符串解析成Alarm集合
            /// <summary>
            /// 根据字符串解析成Alarm集合
            /// </summary>
            /// <param name="Alarm"></param>
            /// <returns></returns>
        public static List<Alarm> GetAlarm(string Alarm)
        {
            List<Alarm> AlarmList = null;
            if (Alarm.Length > 0)
            {
                AlarmList = new List<Alarm>();
                string[] strArray = Alarm.Split('|');
                for (int i = 0; i < strArray.Length - 1; i++)
                {
                    string[] res = strArray[i].Split(';');
                    AlarmList.Add(new Alarm()
                    {
                        AlarmType = res[0],
                        AlarmValue = float.Parse(res[1]),
                        Priorty = int.Parse(res[2]),
                        Note = res[3]
                    });
                }
            }
            return AlarmList;
        }
        #endregion
    }
}